package cc.shacocloud.mirage.demo.java.config;

import cc.shacocloud.mirage.bean.InitializingBean;
import cc.shacocloud.mirage.bean.bind.Configuration;
import cc.shacocloud.mirage.env.Environment;
import cc.shacocloud.mirage.env.EnvironmentAware;
import io.vertx.core.Vertx;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author 思追(shaco)
 * @date 2023/3/7
 */
@Slf4j
@Configuration
public class MirageDemoConfiguration implements InitializingBean, EnvironmentAware {

    private Environment environment;

    private final MirageDemoProperties mirageDemoProperties;
    private final Vertx vertx;

    public MirageDemoConfiguration(MirageDemoProperties mirageDemoProperties, Vertx vertx) {
        this.mirageDemoProperties = mirageDemoProperties;
        this.vertx = vertx;
    }

    /**
     * 初始化回调方法
     *
     * @throws Exception 初始化失败则抛出该例外
     */
    @Override
    public void init() throws Exception {
        log.info("dev配置数据：{}", mirageDemoProperties.getDev());
        log.info("dev配置数据：{}", mirageDemoProperties.getDev1());

        String dev = environment.getProperty("mirage.demo.dev", String.class);
        assert Objects.equals(mirageDemoProperties.getDev(), dev);

        String dev1 = environment.getProperty("mirage.demo.dev1", String.class);
        assert Objects.equals(mirageDemoProperties.getDev1(), dev1);

        // 定时获取配置信息如果配置发生变更，打印的值将发生改变
        vertx.setPeriodic(5000, 5000, id -> log.info("dev1配置数据：{}", mirageDemoProperties.getDev1()));
    }

    /**
     * 在应用上下文启动成功后，会调用该方法注入 {@link Environment}
     *
     * @param environment
     */
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
